package com.ciei.dpagm.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciei.dpagm.common.controller.BaseController;
import com.ciei.dpagm.common.enums.ErrorCodeEnum;
import com.ciei.dpagm.common.enums.LogTypeEnum;
import com.ciei.dpagm.entity.Department;
import com.ciei.dpagm.entity.UserRole;
import com.ciei.dpagm.entity.Users;
import com.ciei.dpagm.service.*;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.JsonUtil;
import com.ciei.dpagm.util.PageParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class UsersController extends BaseController {

	@Autowired
	private UsersService baseUsersService;


	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private LogService logService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private AutoCodeSeedService autoCodeSeedService;

	@Autowired
	private RoleService roleService;

	@RequestMapping("user/farmHouseUserLayout")
	public String farmHouseUserLayout() {
		return "farm/farmHouseUserLayout";
	}

	// webSocket测试页面
	@RequestMapping("testSocketPage")
	public String testSocketPage() {
		return "alarm/testSocketPage";
	}

	//C# HTTP请求测试
	@RequestMapping("get/JSON")
	public JSONObject GetJSON() {
		JSONObject jsonObject = new JSONObject();

		jsonObject.put("LoginName", "1175234");
		jsonObject.put("UserName", "lier");
		return jsonObject;
	}


	@RequestMapping(value = "user/farmHouseUserPage")
	public String farmHouseUserPage() {
		return "farm/farmHouseUsersPage";
	}

	@RequestMapping(value = "user/userPage")
	public String index() {
		return "users/usersPage";
	}

	/**
	 * 加载操作员界面
	 * @return
	 */
	@RequestMapping(value = "operator/operatorLayout")
	public String operatorLayout() {
		return "operator/operatorLayout";
	}

	@RequestMapping(value = "operator/userCompanyTree")
	public String userCompanyTree() {
		return "operator/userCompanyTree";
	}

	@RequestMapping(value = "operator/operatorPage")
	public String operatorPage() {
		return "operator/operatorPage";
	}
	@RequestMapping(value = "users/usersInfo")
	public String getUserInfo() {
		return "users/usersInfo";
	}

	@RequestMapping("user/singleWindowSettingPage")
	public ModelAndView singleWindowSettingPage() {
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		ModelAndView model = new ModelAndView("users/singleWindowSettingPage");
		model.addObject("isSingleWindow", user.getIsSingleWindow());
		return model;
	}

	@RequestMapping(value = "users/updateUserInfo")
	@ResponseBody
	public JSONObject updateUsers(String userName,String address,String email,String post,String mobileTel,String telephone,String userNote) {
		Users m = (Users) SecurityUtils.getSubject().getPrincipal();
		m.setUserName(userName);
		m.setAddress(address);
		m.setEmail(email);
		m.setPost(post);
		m.setMobileTel(mobileTel);
		m.setTelephone(telephone);
		m.setUserNote(userNote);
		return baseUsersService.updateUsers(m);

	}

	//添加用户，添加权限
	@RequestMapping("users/manageAdd")
	@ResponseBody
	public JSONObject manageAdd(HttpServletRequest request){
		Users user = (Users) getInstanceByParameters(Users.class);
		user.setCreateTime(new Timestamp(System.currentTimeMillis()));
		QueryWrapper<Users> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(Users::getLoginName,user.getLoginName());
		wrapper.lambda().eq(Users::getIsDelete,0);
		/* wrapper.lambda().select(Users::getLoginName);*/
		Integer count = baseUsersService.count(wrapper);
		if(count==0){
			baseUsersService.save(user);
		}else {
			return JsonUtil.getSuccess("该用户已被注册");
		}
		Integer userId = user.getUserId();
		PageParam pageParam=getPageParams();
		if( pageParam.params.containsKey("roleIds")){
			String roleId=pageParam.params.get("roleIds").toString();
			if(roleId != null && roleId != "" ){
				String[] arr = roleId.split(",");
				for(String roleIdString:arr){
					Integer newRoleId = Integer.parseInt(roleIdString);
					UserRole userRole = new UserRole();
					userRole.setRoleId(newRoleId);
					userRole.setUserId(userId);
					userRoleService.save(userRole);

				}
			}

		}
		return JsonUtil.getSuccess("OK");
	}


	@RequestMapping(value={"users/image"})
	public void userImage(HttpServletRequest request, HttpServletResponse response,Integer userId, String action, String itemId,String itemValue) throws IOException{
		if("loadImage".equals(action)) {
			baseUsersService.loadImage(response,userId.toString());
		}else {
			baseUsersService.uploadImage(request,response,userId,itemId);
		}
	}

	@RequestMapping("users/updatePassword")
	public String userInfo() {
		return "users/updatePassword";
	}

	//@RequiresPermissions("users:page")
	@RequestMapping("/users/page")
	public ModelAndView usersPage() {
		Map<String, Object> model = new HashMap<String, Object>();
		String id = "index_permission_user";
		//model.put("toolbarData", viewService.loadViewButton(getSessionUser(), id));
		return new ModelAndView("users/usersPage", model);
	}

	@RequestMapping("vue/user/loadUserByDepartment")
	@ResponseBody
	public JSONObject loadUserByDepartment(@RequestBody JSONObject page){
		PageParam pageParam=getPageParams(page);
		return departmentService.loadUserByDepartment(pageParam);
	}

	@RequestMapping(value = "users/load")
	@ResponseBody
	public JSONObject loadUserData( HttpServletRequest request) {
		QueryWrapper<Users> wrapper=new QueryWrapper();
		PageParam ps=getPageParams();
		Map<String, Object> params=ps.params;
		int posStart =ps.posStart;
		int count =ps.count;
		int totalCount=0;
		String testWords=null;
		if(ps.params.containsKey("userName")){
			testWords=ps.params.get("userName").toString();
		}
		if(!StringUtils.isBlank(testWords)) {
			String finalTestWords = testWords;
			wrapper.lambda().and(w->w.like(Users::getUserName, finalTestWords).
					or().like(Users::getLoginName, finalTestWords));
		}
		wrapper.lambda().eq(Users::getIsDelete,0);
		List<Users> list = baseUsersService.findPage(posStart, count,wrapper);
		JSONObject json = new JSONObject();
		JSONArray jarr = new JSONArray();
		int index = 1;
		for (Users m : list) {
			Map<String, Object> mobj = new HashMap<String, Object>();
			mobj.put("rowNumber", index++);
			mobj.put("id", m.getUserId());
			mobj.put("userId", m.getUserId());
			mobj.put("loginName", m.getLoginName());
			mobj.put("userName", m.getUserName());
			mobj.put("email", m.getEmail());
			mobj.put("mobilTel", m.getMobileTel());
			mobj.put("telephone", m.getTelephone());
			mobj.put("address", m.getAddress());
			//获取用户的所有角色roleId
			List<UserRole>  userRoleList = userRoleService.findByProperty("user_id",m.getUserId());
			List<String>  roleNames = new ArrayList<>();
			if(userRoleList.size()>0){
				for(UserRole userRole:userRoleList){
					roleNames.add(roleService.findById(userRole.getRoleId()).getRoleName());
				}
			}
			mobj.put("roleNames", roleNames);
			if(m.getDepartmentId()!=null){
				if(departmentService.findById(m.getDepartmentId()) != null){
					mobj.put("departmentName", departmentService.findById(m.getDepartmentId()).getDepartmentName());
				}
			}else {
				mobj.put("departmentName", "");
			}
			jarr.add(mobj);
		}
		totalCount = baseUsersService.count(wrapper);
		json.put(APP.DATA, jarr);
		json.put(APP.TOTAL_COUNT, totalCount);
		json.put(APP.POS, posStart);
		return json;
	}

	//@RequiresPermissions("users:resetPassword")
	@RequestMapping(value = "users/resetPassword")
	@ResponseBody
	public JSONObject resetPassword(String userIds) {
		return baseUsersService.updatePassword(userIds);
	}

	//@RequiresPermissions("users:role:addUserRole")
	@RequestMapping("/users/role/addUserRole")
	@ResponseBody
	public JSONObject addUserRole(Integer userId,String str){
		return userRoleService.addUsersRole(baseUsersService.findById(userId),str);
	}
	/**
	 * 修改密码tab页面
	 * @return
	 */
	//@RequiresPermissions("password:page")
	@RequestMapping("/password/page")
	public ModelAndView passwordPage() {
		Map<String, Object> model = new HashMap<String, Object>();
		String id = "index_manageTabbar_password";
		//model.put("toolbarData", viewService.loadViewButton(getSessionUser(), id));
		return new ModelAndView("information/password/passwordModify", model);
	}

	@RequestMapping(value = "password/modify")
	@ResponseBody
	public JSONObject modifyPassword(String oldPassword , String newPassword) {
		Users user = (Users) getSessionUser();
		return baseUsersService.updatePassword(user.getLoginName(), oldPassword, newPassword);
	}

//修改用户，用户权限

	//@RequiresPermissions("users:update")
	@RequestMapping(value = "users/update")
	@ResponseBody
	public JSONObject updateUsers(HttpServletRequest request) throws ClassNotFoundException, IllegalAccessException {
		Users user = (Users) getInstanceByParameters(Users.class);
		Integer userId = user.getUserId();
		//userId为1不能被修改
		if(userId == 1) {
			if(user.getLocked() != 0) {
				return JsonUtil.getFail("该用户不能被锁定！");
			}
		}
		//登录名不能重复
		QueryWrapper<Users> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(Users::getLoginName,user.getLoginName());
		Integer count = baseUsersService.count(wrapper);
		if(count==0){
			baseUsersService.saveOrUpdate(user);
		}else if(user.getLoginName().equals(baseUsersService.findById(user.getUserId()).getLoginName())){
			baseUsersService.saveOrUpdate(user);
		}else {

			return JsonUtil.getSuccess("该用户已被注册");
		}
		/*logService.addLog("用户管理", "修改用户信息", "系统管理", before,after, 0, null);*/
		PageParam pageParam=getPageParams();

		if( pageParam.params.containsKey("roleIds")){
			String roleId=pageParam.params.get("roleIds").toString();
			if(roleId != null && roleId != ""){
				String[] arr = roleId.split(",");
				userRoleService.delete(userId);
				for(String roleIdString:arr){
					Integer newRoleId = Integer.parseInt(roleIdString);
					UserRole userRole = new UserRole();
					userRole.setRoleId(newRoleId);
					userRole.setUserId(userId);
					userRoleService.save(userRole);

				}
			}
		}
		// logService.addLog("Users","修改用户及权限","系统管理",null,null,0,null);

		return JsonUtil.getSuccess("OK");

	/*	List<Users> userList=usersService.findByProperties(new String[] {"loginName","isDelete"}, new Object[] {loginName,0});

	//找到修改前的对象
		Users users = usersService.findById(user.getUserId());

		if(user.getUserId() == 1) {
			if(user.getLocked() != 0) {
				return JsonUtil.getFail("该用户不能被锁定！");
			}
		}*/

		/*	Role role = roleService.findById(roleId);

			List<Users> list = usersService.findByProperties(new String[] {"userName","company.companyId","isDelete"}, new Object[] {user.getUserName(),companyId,0});
			if(list != null && list.size()>0) {
				Users r = list.get(0);
				if(!r.getUserId().equals(user.getUserId())) {
					return JsonUtil.getFail("该用户名已经存在！");
				}
			}
			Users u = (Users) findSessionKey(APP.SESSION_KEY_CURRENT_USER);

		if(!userList.isEmpty()) {
			if(!user.getUserId().equals(userList.get(0).getUserId())) {
				JSONObject json = JsonUtil.getFail("登陆账号重复，请重新输入");
				return json;
			}else {
				 user.setRoleId(roleId);
				 user.setDepartmentId(departmentId);
				 user.setCompanyId(companyId);
				 user = (Users) ClassUtil.emptyStringConvertNull(user);

				 List<Map<String ,Object>>  lists = logService.compareTwoClass(users, user);
				 String before = "";
				 String after = "";
				 for(Map<String ,Object> map:lists) {
					 String name = (String) map.get("name");
					if(name.equals("department")) {
						String oldDepart =departmentService.getDepartmentName(users.getDepartmentId());
						List<Department> listD = departmentService.findByProperty("departmentId", departmentId);
						if(listD !=null && listD.size()>0) {
							String newDepart = listD.get(0).getDepartmentName();
							if(oldDepart != null) {
								if(!oldDepart.equals(newDepart)) {
									before = before + name + ":" + oldDepart + " ";
									after = after + name + ":" + newDepart + " ";
								}
							}else {
								if(newDepart != null) {
									before = before + name + ":" + " ";
									after = after + name + ":" + newDepart + " ";
								}
							}
						}

					}
					else if(name.equals("role")) {
						String oldDepart = roleService.getRoleName(users.getRoleId());
						String newDepart   = roleService.findById(roleId).getRoleName();
						if(oldDepart != null) {
							if(!oldDepart.equals(newDepart)) {
								before = before + name + ":" + oldDepart + " ";
								after = after + name + ":" + newDepart + " ";
							}
						}else {
							if(newDepart != null) {
								before = before + name + ":" + " ";
								after = after + name + ":" + newDepart + " ";
							}
						}
					}else {
					 Object newName =  map.get("new");
					 Object oldName =  map.get("old");
					 before = before + name + ":" + oldName + " ";
					 after = after + name + ":" + newName + " ";
					}
				 }
				 logService.addLog("用户管理","修改用户信息", "系统管理", before,after, 0, null);
				 return usersService.updateUsers(user);
			   }
		}else {

		user.setRoleId(roleId);
		user.setDepartmentId(departmentId);
		user.setCompanyId(companyId);
		user = (Users) ClassUtil.emptyStringConvertNull(user);

		*//*List<Company> companyList = companyService.findByProperties(
				new String[] {"companyId", "isDelete"}, new Object[] {companyId, 0});
		user.setCompanyName(companyList.get(0).getCompanyName());*//*

		List<Map<String ,Object>>  lists = logService.compareTwoClass(users, user);
		 String before = "";
		 String after = "";
		 for(Map<String ,Object> map:lists) {
			 String name = (String) map.get("name");
			if(name.equals("department")) {
				String oldDepart = departmentService.getDepartmentName(users.getDepartmentId());
				String newDepart = departmentService.findById(departmentId).getDepartmentName();
				if(oldDepart != null) {
					if(!oldDepart.equals(newDepart)) {
						before = before + name + ":" + oldDepart + " ";
						after = after + name + ":" + newDepart + " ";
					}
				}else {
					if(newDepart != null) {
						before = before + name + ":" + " ";
						after = after + name + ":" + newDepart + " ";
					}
				}
			}
			else if(name.equals("role")) {
				String oldDepart = roleService.getRoleName(users.getRoleId());
				String newDepart   = roleService.findById(roleId).getRoleName();
				if(oldDepart != null) {
					if(!oldDepart.equals(newDepart)) {
						before = before + name + ":" + oldDepart + " ";
						after = after + name + ":" + newDepart + " ";
					}
				}else {
					if(newDepart != null) {
						before = before + name + ":" + " ";
						after = after + name + ":" + newDepart + " ";
					}
				}
			}else {
			 Object newName =  map.get("new");
			 Object oldName =  map.get("old");
			 before = before + name + ":" + oldName + " ";
			 after = after + name + ":" + newName + " ";
			}
		 }
		 logService.addLog("用户管理", "修改用户信息", "系统管理", before,after, 0, null);
		 return usersService.updateUsers(user);

		} return usersService.updateUsers(user);*/
	}

	@RequestMapping(value = "users/getUsersList")
	@ResponseBody
	public JSONObject loadDepartmentList() {
		return baseUsersService.loadUsersList();
	}

	@RequestMapping("users/userLayout")
	public String userLaytout() {
		return "users/userLayout";
	}

	//farmusersform
	@RequestMapping("farm/farmHouseUsersForm")
	public String farmusersform() {
		return "farm/farmHouseUsersForm";
	}

	@RequestMapping("users/userForm")
	public String loginPage() {
		return "users/userForm";
	}

	@RequestMapping(value = "users/loadForm")
	@ResponseBody
	public JSONObject loadForm(Integer userId) {
		//Users user=(Users)findSessionKey(APP.SESSION_KEY_CURRENT_USER);
		Users user= baseUsersService.findById(userId);
		//部门Id
		Integer departMentId = user.getDepartmentId();
		String departmentName = null;
		if(departMentId != null){
			Department department = departmentService.findById(departMentId);
			if (department !=null){
				departmentName = department.getDepartmentName();
			}
		}
		//获取用户的所有角色roleId
		List<UserRole>  userRoleList = userRoleService.findByProperty("user_id",user.getUserId());
		//用户的角色名
		String roleNames = "";
		//用户的角色Id
		String roleIds = "";
		if(userRoleList.size()>0){
			for(UserRole userRole:userRoleList){
				roleNames += roleService.findById(userRole.getRoleId()).getRoleName()+",";
				roleIds += userRole.getRoleId()+",";
			}
			//最后一个逗号的位置
			int index = roleNames.lastIndexOf(",");
			int indexRoleId = roleIds.lastIndexOf(",");
			roleNames = roleNames.substring(0,index);
			roleIds.substring(0,indexRoleId);
		}

		JSONObject json=new JSONObject();
		if(user!=null) {
			json=JsonUtil.getSuccess("");
			json.put("data", user);
			json.put("companyId", user.getCompanyId());
			json.put("password", user.getPassword());
		}else{
			json=JsonUtil.getFail("没有找到用户信息");
		}
		json.put("roleName",roleNames);
		json.put("departmentName",departmentName);
		json.put("roleIds",roleIds);
		return json;
	}


	@RequestMapping(value = "users/logout")
	@ResponseBody
	public Object logout() {
		Map<String,Object> data = new HashMap<String,Object>();
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
			data.put("results", "OK");
		}
		return data;
	}



	@RequestMapping("user/updateIsSingleWin")
	@ResponseBody
	public JSONObject updateIsSingleWin(Integer isSingleWindow) {
		JSONObject json = new JSONObject();
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		user.setIsSingleWindow(isSingleWindow);
		baseUsersService.updateById(user);
		json = JsonUtil.getSuccess("");
		return json;
	}



	@RequestMapping("vue/user/load")
	@ResponseBody
	public JSONObject loadVue(@RequestBody JSONObject page) {
		PageParam pageParam = getPageParams(page);
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		return baseUsersService.loadVue(pageParam,user.getCompanyId());
	}

	@RequestMapping("vue/user/delete")
	@ResponseBody
	public JSONObject deleteVue(@RequestBody JSONObject requestJson) {
		return baseUsersService.delete(requestJson);
	}

	@RequestMapping("vue/user/add")
	@ResponseBody
	public JSONObject addVue(@RequestBody JSONObject jsonObject) {
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		return baseUsersService.addOrUpdateUsers(jsonObject,"add",user);
	}

	@RequestMapping("vue/user/update")
	@ResponseBody
	public JSONObject updateVue(@RequestBody JSONObject jsonObject) {
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		return baseUsersService.addOrUpdateUsers(jsonObject,"edit",user);
	}


	/**
	 * 重置密码，获取信息
	 * @author pp
	 */
	@RequestMapping("user/resetPassword")
	@ResponseBody
	public JSONObject resetPassword(@RequestBody JSONObject data) {
		Users currentUser = (Users)SecurityUtils.getSubject().getPrincipal();
		return baseUsersService.resetPassword(data, currentUser);
	}

	/**
	 * 发送邮件
	 * @author pp
	 */
	@RequestMapping("vue/user/send")
	@ResponseBody
	public JSONObject sendVue(@RequestBody JSONObject jsonObject) {
		Users user = (Users) SecurityUtils.getSubject().getPrincipal();
		return baseUsersService.sendVue(jsonObject, user);
	}

	@RequestMapping("user/changePassword")
	@ResponseBody
	public JSONObject changePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
		if (StringUtils.isEmpty(newPassword)) {
			return JsonUtil.getFail(ErrorCodeEnum.INVALID_PARAM, "请输入新密码");
		}
		if (oldPassword.equals(newPassword)) {
			return JsonUtil.getFail(ErrorCodeEnum.INVALID_PARAM, "新密码不能与旧密码相同");
		}
		Users currentUser = (Users)SecurityUtils.getSubject().getPrincipal();
		return baseUsersService.changePassword(oldPassword, newPassword, currentUser);
	}

	@RequestMapping("user/getAllOperatorOnDuty")
	@ResponseBody
	public JSONObject getAllOperatorOnDuty() {
		return baseUsersService.getAllOperatorOnDuty();
	}

	@RequestMapping("user/getUserListByUserName")
	@ResponseBody
	public JSONObject getUserListByUserName(@RequestParam("userName") String userName) {
		return baseUsersService.getUserListByUserName(userName);
	}

	@RequestMapping("user/getRoleIdsByUserId")
	@ResponseBody
	public JSONObject getRoleIdsByUserId(Integer userId) {
		return baseUsersService.getRoleIdsByUserId(userId);
	}

	@RequestMapping("user/setUserRoles")
	@ResponseBody
	public JSONObject setUserRoles(@RequestBody JSONObject configJson) {
		return baseUsersService.setUserRoles(configJson);
	}
}
